import { _decorator, Component, Node, Vec3, RigidBody, BoxCollider, Quat, math, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Dice')
export class Dice extends Component {
    @property
    initialForce: Vec3 = new Vec3(0, 10, 10);

    @property
    diceCount: number = 3;

    @property(Node)
    touzi: Node;

    @property(Node)
    touzi1: Node;

    @property(Node)
    ground: Node;

    @property(Label)
    resultLabel: Label;

    private isRolling: boolean = false;
    private rigidBody: RigidBody;
    private dices: Node[] = [];

    onLoad() {
        const groundCollider = this.ground.addComponent(BoxCollider);
        groundCollider.size = new Vec3(50, 1, 50);

        this.rigidBody = this.touzi.addComponent(RigidBody);
    this.touzi.addComponent(BoxCollider);
    this.rigidBody.useGravity = true;
    this.rigidBody.mass = 100;

    this.rigidBody = this.touzi1.addComponent(RigidBody); // 添加刚体组件
    this.touzi1.addComponent(BoxCollider); // 添加盒子碰撞器
    this.rigidBody.useGravity = true; // 启用重力
    this.rigidBody.mass = 100; // 设置质量


        this.dices.push(this.touzi);
        this.dices.push(this.touzi1);
        this.rollDices();
    }

    public click(): void {
        this.rollDices();
    }

    rollDices() {
        if (!this.isRolling) {
            this.isRolling = true;
            this.schedule(this.checkIfDiceStopped, 0.5);
            for (let i = 0; i < this.dices.length; i++) {
                const dice = this.dices[i];
                dice.setPosition(0, 10, 0);
                const randomRotation = new Vec3(Math.random() * 360, Math.random() * 360, Math.random() * 360);
                dice.setRotationFromEuler(randomRotation);
                const rigidBody = dice.getComponent(RigidBody);
                rigidBody.clearState();
                rigidBody.setLinearVelocity(new Vec3(0, 0, 0));
                rigidBody.setAngularVelocity(new Vec3(0, 0, 0));
                rigidBody.applyForce(this.initialForce);
                rigidBody.applyTorque(new Vec3(Math.random(), Math.random(), Math.random()).multiplyScalar(10));
            }
        }
    }

    private v1: Vec3 = new Vec3();
    private v2: Vec3 = new Vec3();

    checkIfDiceStopped() {
        for (let i = 0; i < this.dices.length; i++) {
            const rigidBody = this.dices[i].getComponent(RigidBody);
            rigidBody.getLinearVelocity(this.v1);
            rigidBody.getAngularVelocity(this.v2);
            if (this.isZero(this.v1) && this.isZero(this.v2)) {
                this.isRolling = false;
            }
        }

        if (!this.isRolling) {
            this.unschedule(this.checkIfDiceStopped);
            this.calculateDiceResults();
        }
    }

    isZero(v3: Vec3): boolean {
        return v3.lengthSqr() === 0;
    }

    calculateDiceResults() {
        let totalDiceValue:number = 0;
        for (let i = 0; i < this.dices.length; i++) {
            const dice = this.dices[i];
            let diceWorldRotation = new Quat();
            dice.getWorldRotation(diceWorldRotation);
            totalDiceValue += this.calculateDiceValue(diceWorldRotation);
        }
        this.resultLabel.string = totalDiceValue + "";
    }

    calculateDiceValue(diceRotation: Quat) {
        const faceDirections = [
            new Vec3(0, 1, 0),   // 骰子顶部
            new Vec3(0, 0, 1),   // 骰子正面
            new Vec3(1, 0, 0),   // 骰子右侧
            new Vec3(-1, 0, 0),  // 骰子左侧
            new Vec3(0, 0, -1),   // 骰子背面
            new Vec3(0, -1, 0),  // 骰子底部
            
        ];
    
        let maxDot = -2; // 初始化为一个足够小的值
        let diceValue = 0;
    
        for (let i = 0; i < faceDirections.length; i++) {
            let direction = new Vec3();
            Vec3.transformQuat(direction, faceDirections[i], diceRotation);
            let dot = Vec3.dot(direction, new Vec3(0, 1, 0)); // 检查朝向和骰子顶部的点积
            if (dot > maxDot) {
                maxDot = dot;
                diceValue = i + 1; // 点数从1开始
            }
        }
    
        return diceValue;
    }
    
}
